var wcmp = require('../wechat/index').wcmp;
var moment = require("moment");
var dates = require("../common/dates");
var async = require("async");
var memberAccountServiceNative = require("../services/MemberAccountService");
var errorHandler = require('../common/errorHandler');

var MemberAccountController = {
	accountList: function (req, res, next) {
	    var memberAccountService = errorHandler.errorToResponse(req, res, memberAccountServiceNative);

		var memberId = req.params.id;
		var type = req.query.type;
		var allType = ['deposit', 'manual-update', 'refund', 'pay']
		if (type == "pay") {
			allType = ['refund', 'pay']
		} else if (type == "deposit") {
			allType = ['deposit', 'manual-update']
		}
		var month = req.query.month;
		if (!month) {
			month = moment().format("YYYY-MM");
		}
		var resultData = {};

		async.series([
				function (cb) {
					memberAccountService.getAccount(memberId, function (err, account) {
						if (!account) {
							account = {balance: 0}
						}
						resultData.account = account;
						cb(err, account);
					})
				},
				function (cb) {
					var types = ['deposit', 'manual-update']
					memberAccountService.getAccountTotal(memberId, types, function (err, total) {
						resultData.accountTotalDeposit = total;
						cb(err, total);
					})
				},
				function (cb) {
					var types = ['refund', 'pay']
					memberAccountService.getAccountTotal(memberId, types, function (err, total) {
						resultData.accountTotalPay = total;
						cb(err, total);
					})
				},
				function (cb) {
					memberAccountService.getAccountTxList(memberId, allType, dates.monthStart(month, 2), dates.monthEnd(dates.monthStart(month, 0)), function (err, txList) {
						resultData.txs = txList;
						resultData.count = txList.length;
						cb(err, resultData.txs);
					});
				}],
			function (err, result) {
				res.send(resultData);
			})
	},
	getOneAccountTx: function (req, res, next) {
	    var memberAccountService = errorHandler.errorToResponse(req, res, memberAccountServiceNative);

		var txId = req.params.id;
		memberAccountService.getAccountOneTx(txId, function (err, tx) {
			if (err) {
				return res.status(400).json({error: "参数错误"});
			}
			res.send(tx);
		})
	}
};

module.exports = MemberAccountController;